# -*- coding: utf8 -*-

import struct
import zlib
from base64 import b64decode, b64encode
from project.sqlite3_db.table import Table

class TableImageVector100( Table ):

    _table_name = "image_vector100"

    def create( self ):
        cur = self.getCursor()

        # Create table
        cur.execute(
            "CREATE TABLE IF NOT EXISTS image_vector100 ("+
            "id INTEGER PRIMARY KEY, "+
            "image_id INTEGER, "+
            "orientation INTEGER, "+
            "vector BLOB)"
        )
        cur.execute(
            "CREATE INDEX IF NOT EXISTS images ON image_vector100 (image_id, orientation)"
        )
        cur.close()
        return


    def insert_image_v100( self, image_id, orientation, vector ):
        v_str = b64encode(b"".join([ struct.pack("<B", v) for v in vector ]))
        cur = self.getCursor()
        cur.execute(
            "INSERT INTO image_vector100("+
            "image_id, orientation, vector"
            ") VALUES (?, ?, ?)", (
                image_id, orientation, v_str
            )
        )
        self.getConnection().commit()
        v_id = cur.lastrowid
        cur.close()
        return v_id


    def get_image_vectors( self, image_id ):
        cur = self.getCursor()
        cur.execute(
            "SELECT * FROM image_vector100 WHERE image_id=:id ORDER BY orientation ASC",
            {"id":image_id}
        )
        vectors = cur.fetchall()
        cur.close()
        for i in range(len(vectors)):
            v_str = b64decode(vectors[i]["vector"])
            vectors[i]["vector"] = tuple()
            for n in range(len(v_str)):
                vectors[i]["vector"] += ( ord(v_str[n:n+1]), )
        return vectors


    pass
